import openpyxl
import requests
import parsel
from openpyxl.drawing.image import Image
import os


def download_image(image_url, save_path):
    response = requests.get(image_url, stream=True)
    if response.status_code == 200:
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(1024):
                f.write(chunk)


def get_image_size(image_path):
    try:
        img = Image(image_path)
        return img.width, img.height
    except:
        return 0, 0


def calculate_scale_factor(img_width, img_height, cell_width, cell_height):
    img_width = img_width if img_width > 0 else cell_width
    img_height = img_height if img_height > 0 else cell_height
    cell_width = cell_width if cell_width is not None else 60
    cell_height = cell_height if cell_height is not None else cell_width * 2
    width_scale = cell_width / img_width
    height_scale = cell_height / img_height
    return min(width_scale, height_scale)


def crawl_images_to_excel():
    # Select the sheet by name
    wb = openpyxl.Workbook()
    sheet = wb.active

    image_url = picture_baidu()
    image_filename = "image_ceshi.jpg"
    # image_filename = os.path.basename('https://img2.baidu.com/it/')
    download_image(image_url, image_filename)

    # Get the size of the image and the cell
    img_width, img_height = get_image_size(image_filename)
    cell_width = sheet.column_dimensions['B'].width  # Assuming the images are inserted in column B
    cell_height = sheet.row_dimensions[1].height  # Assuming one image per row
    # Calculate the scaling factor
    scale_factor = calculate_scale_factor(img_width, img_height, cell_width, cell_height)

    # Add the title and image to the worksheet
    cell_to_insert = "A1"
    sheet[cell_to_insert] = "title"
    img = Image(image_filename)
    img.width = img_width * scale_factor
    img.height = img_height * scale_factor
    sheet.add_image(img, "B1")

    cell_to_insert = "A2"
    sheet[cell_to_insert] = "t2"
    img = Image(image_filename)
    img.width = img_width * scale_factor
    img.height = img_height * scale_factor
    sheet.add_image(img, "B2")
    print(f'图片路径:{image_filename}')
    # Remove the downloaded image file (optional)
    # Comment out this line if you want to keep the images locally

    # Save the workbook
    wb.save('img_excel.xlsx')
    if os.path.exists(image_filename):
        os.remove(image_filename)


def picture_baidu():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        'Cookie': 'BDqhfp=%E4%BC%98%E9%85%B7%26%26NaN-1undefined%26%260%26%261; BIDUPSID=6CCDFE96D26C5EAC4E60DD16D7956999; PSTM=1690285397; BAIDUID=6CCDFE96D26C5EAC5246D9F4F972C1E7:FG=1; H_PS_PSSID=; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BAIDUID_BFESS=6CCDFE96D26C5EAC5246D9F4F972C1E7:FG=1; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; ab_sr=1.0.1_ZDA5YWZkYmJlYzk3MzUxMWZiN2U5ODdhYjFlODM4ZDU1ZDFlYzYxOGU4YWU3MDc1OGI3ZTRhMmI0NzkyNDJiODA2NTljNGVjYWE2MTE4YTIwYmU4NzQ2YjcyY2Q4ODRmMDQyMWY2NWQwMzhiOTQ4NzVkZjY4YjQ1ZWIyNzhkZDRmNzM2NTFhOTc2YjdlZjRiNGExZjZlYTYxMWI4MTBhNw==',
        'Accept': '/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Host': 'image.baidu.com',
        'Sec-Ch-Ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
        'Sec-Ch-Ua-Mobile': '?0',
        'Sec-Ch-Ua-Platform': '"Windows"',
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'none',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
    }
    url = 'https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E4%BC%98%E9%85%B7&step_word=&hs=0&pn=0&spn=0&di=46137345&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=2415131396%2C2185010349&os=1891517611%2C3393231992&simid=3552389615%2C385807329&adpicid=0&lpn=0&ln=795&fr=&fmq=1690291920985_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=11&oriquery=&objurl=https%3A%2F%2Fwx2.sinaimg.cn%2Fmw690%2F006VqaVply8hg38eic97oj30u01hc1h2.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fojtk5_z%26e3Bv54AzdH3FnbblmmbbcmAzdH3FNwJba1f9H&gsm=1e&rpstart=0&rpnum=0&islist=&querylist=&nojc=undefined&dyTabStr=MCwxLDYsNCw1LDMsMiw4LDcsOQ%3D%3D'
    response = requests.get(url, headers=headers)
    response.encoding = 'utf-8'
    select = parsel.Selector(response.text)
    img_url = select.css('div.img-wrapper>img::attr(src)').get()
    print(img_url)
    return img_url


if __name__ == '__main__':
    excel_file = "img_excel.xlsx"
    sheet_name = "Sheet1"
    #
    crawl_images_to_excel()
